package com.example.joke.base.navigationbar

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

abstract class AbsNavigationBar<P : AbsNavigationBar.Builder.AbsNavigationParams>(val mParams: P) : INavigationBar {

    private lateinit var mNavigationView: View

    fun getParams() : P {
        return mParams
    }
    init {
        createAndBindView()
    }


    // 绑定和创建View
    private fun createAndBindView() {
        // 1. 创建view
        if (mParams.mParent == null) {
            // 如果用户调用时没有传根布局id，则获取activity根布局的第0个作为父布局
            val activity: Activity = mParams.mContext as Activity
            //            val activityRoot: ViewGroup = activity.findViewById(android.R.id.content)
            // 如果自己的activity的xml文件是以LinearLayout或者LinearLayoutCompat为根布局，用content的第0个孩子作为父布局不会有什么问题，
            // 但如果自己的activity的xml文件是以Relativelayout或者ConstraintLayout、FrameLayout等为根布局，这么用就会出现控件重叠的问题
            // 解决如下：不用content的第0个孩子，而是使用decorView(FrameLayout)的第0个孩子(LinearLayout)
            val activityRoot: ViewGroup = activity.window.decorView as ViewGroup
            mParams.mParent = activityRoot.getChildAt(0) as ViewGroup
        }

        if (mParams.mParent == null) {
            return
        }

        mNavigationView = LayoutInflater.from(mParams.mContext)
            .inflate(bindLayoutId(), mParams.mParent, false)

        // 2. 添加view
        mParams.mParent?.addView(mNavigationView, 0)
        applyView()
    }

    protected fun setText(viewId: Int, text: String) {
        val textView = mNavigationView.findViewById<TextView>(viewId)
//        val textView = findViewById(viewId)
        if (!text.isNullOrEmpty()) {
            textView.visibility = View.VISIBLE
            textView.text = text
        }
    }

    protected fun setIcon(viewId: Int, resId: Int) {
        val imageView = mNavigationView.findViewById<ImageView>(viewId)
//        val textView = findViewById(viewId)
        if (resId != 0) {
            imageView.visibility = View.VISIBLE
            imageView.setImageResource(resId)
        }
    }
    protected fun setOnClickListener(viewId: Int, listener: OnClickListener) {
        mNavigationView.findViewById<View>(viewId).setOnClickListener(listener)
    }

    fun <T : View> findViewById(viewId: Int) : T {
        return mNavigationView.findViewById(viewId) as T
    }

    abstract class Builder(private val context: Context, private val parent: ViewGroup?) {

        abstract fun <P : AbsNavigationParams> builder() : AbsNavigationBar<P>
        open class AbsNavigationParams(val mContext: Context, var mParent: ViewGroup?) {

        }
    }
}